package serv

import (
	"errors"
	"gorm.io/gorm"
	"server/internal/app/model"
	"server/internal/database"
	"server/pkg/tools"
	"strings"
	"time"
)

var User = new(user)

type user struct {
	model.User
	GroupName  string `json:"group_name"`
	TissueName string `json:"tissue_name"`
	TissueArr  []int  `json:"tissue_arr" gorm:"-"`
	Qrcode     string `json:"qrcode"`
}

// Reads 列表
func (a user) Reads(Db *gorm.DB) (*gorm.DB, []user, int64) {
	var list []user
	var total int64
	Db.Model(&a.User).
		Select("user.*,(select name from user_group where id = user.group_id) as group_name,"+
			"(select name from tissue  where id = user.tissue_id) as tissue_name").
		//Order("user.create_time desc").
		Where("id<>?", 1).
		Find(&list).Offset(-1).Count(&total)
	return Db, list, total
}

// Read 单条
func (a user) Read(id any) (*gorm.DB, user) {
	Db := database.DB

	detail := user{}
	Db.Model(&a.User).
		Select("user.*,(select name from user_group where id = user.group_id) as group_name").
		Where("id =?", id).First(&detail)
	detail.Password = ""
	detail.TissueArr = tools.StringArrToIntArr(strings.Split(Tissue.GetTissueIdArr(detail.TissueId), ","))
	return Db, detail

}

// Create 新增
func (a user) Create(data model.User) (model.User, error) {
	Db := database.DB
	err := Db.Transaction(func(tx *gorm.DB) error {

		if data.Username != "" {
			detail := user{}
			tx.Model(&data).Where("username =?", data.Username).First(&detail)
			if detail.ID > 0 {
				return errors.New("用户已存在")
			}
		}

		t := time.Now()
		data.CreateTime = int(t.Unix())
		data.UpdateTime = int(t.Unix())
		if data.Password != "" {
			data.Password = tools.GetMd5String(data.Password)
		}
		data.City = Area.GetAreaName(data.AreaId)
		data.Tissue = Tissue.GetAreaName(data.TissueId)
		//创建用户
		if err := tx.Create(&data).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}

		//userMoney := UserMoney{}
		//userMoney.UserID = a.ID
		//userMoney.Balance = 0.00
		//userMoney.Status = "1"
		////创建钱包
		//if err := tx.Create(&userMoney).Error; err != nil {
		//	// 返回任何错误都会回滚事务
		//	return err
		//}

		// 返回 nil 提交事务
		return nil
	})

	return data, err
}

// Update 编辑
func (a user) Update(data model.User) (*gorm.DB, error) {
	Db := database.DB
	detail := user{}
	if data.Username != "" {
		Db.Model(&data).
			Where("username =? and id <> ?", data.Username, data.ID).First(&detail.User)
		if detail.ID > 0 {
			return Db, errors.New("用户名重复")
		}
	}
	data.City = Area.GetAreaName(data.AreaId)
	data.Tissue = Tissue.GetAreaName(data.TissueId)
	t := time.Now()
	data.UpdateTime = int(t.Unix())
	Db = Db.Updates(&data)
	return Db, nil

}

// Delete 删除
func (a user) Delete(ids []int) *gorm.DB {
	Db := database.DB
	return Db.Delete(&a.User, ids)

}
